package com.example.chapter6.controller;

import com.example.chapter6.model.UserCredentials;
import com.example.chapter6.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
public class AuthenticationController {
    @PostMapping("/login")
    public ResponseEntity<?> authenticateUser(@RequestBody UserCredentials credentials) {
        // 实现身份验证逻辑
        // 假设用户名和密码验证成功
        boolean isAuthenticated = authenticate(credentials.getUsername(),
                credentials.getPassword());
        if (isAuthenticated) {
            String token = JwtUtil.generateToken(credentials.getUsername());
            return ResponseEntity.ok(new TokenResponse(token));
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body
                    ("Invalid Credentials");
        }
    }

    @GetMapping("/validateToken")
    public ResponseEntity<?> validateToken(@RequestHeader("Authorization") String authHeader) {
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7); // 移除"Bearer "前缀
            try {
                Claims claims = JwtUtil.parseToken(token);
                // 进一步的验证逻辑（如检查 Token 是否过期）
                // 返回 Token 解析后的信息（如用户名）
                return ResponseEntity.ok("Token valid for user: " + claims.getSubject());
            } catch (Exception e) {
                // Token 验证失败的处理逻辑
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body
                        ("Invalid Token: " + e.getMessage());
            }
        } else {
            // 没有提供 Token 的处理逻辑
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("No Token Found");
        }
    }

    private boolean authenticate(String username, String password) {
        // 实现真实的身份验证逻辑
        // 这里简化为示例代码
        return "validUser".equals(username) && "validPassword".equals
                (password);
    }

    // 用于封装 JWT 的响应对象
    private static class TokenResponse {
        private String token;

        public TokenResponse(String token) {
            this.token = token;
        }

        public String getToken() {
            return token;
        }

        public void setToken(String token) {
            this.token = token;
        }
    }
}
